import { reqLogin, reqGetUserInfo, reqGetUserDetailById } from '@/api/user'
// import router from '@/router'
import { setToken, getToken, removeToken } from '@/utils/auth'
// import { resetRouter } from '@/router'

const state = {
  token: getToken() || '',
  userInfo: {}
}
const mutations = {
  // 设置token
  setMyToken(state, token) {
    state.token = token
    // 将token储存到cookie
    setToken(token)
  },
  // 设置用户资料
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  // 退出删除token
  removeToken(state) {
    state.token = ''
    removeToken()
  },
  // 删除个人资料
  delUserInfo(state) {
    state.userInfo = {}
  }

}

const actions = {
  // 获取token的异步
  // async getMyToken(context, loginFrom) {
  //   const data = await login(loginFrom)
  //   console.log(data, 1111)
  //   const res = data.data.data
  //   // console.log(res)
  //   context.commit('setMyToken', res)
  //   if (data.status === 200 && data.data.code === 10000) {
  //     router.push('/')
  //   }
  // }
  // 登录的异步
  login(context, data) {
    return new Promise((resolve, reject) => {
      reqLogin(data).then((res) => {
        console.log(res, 7777)
        context.commit('setMyToken', res.data)
        resolve(res)
      }).catch((err) => {
        console.log(err)
        reject(err)
      })
    })
  },
  // 获取用户治疗异步
  async getUserInfo(context) {
    const { data } = await reqGetUserInfo()
    console.log(data, 999)
    const { data: data2 } = await reqGetUserDetailById(data.userId)
    console.log(data2)
    const res = {
      ...data,
      ...data2
    }
    console.log(res, 5555)
    context.commit('setUserInfo', res)
    return res
  },
  // 退出登录异步
  logout(context) {
    context.commit('removeToken')
    context.commit('delUserInfo')
  }

}
const getters = {

}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}

